package top.jandmla.excel.util;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.io.FileUtils;
import top.jandmla.excel.configParam.FilePathParam;
import top.jandmla.excel.bean.Test;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class Backups {

    /**
     * 写入文件
     *
     * @param list1    所有的信息列表
     * @param filename 文件名
     * @return 本地文件地址
     */
    public static String writeExcel(List<List<Test>> list1, String filename) {

        FilePathParam filePathParam = new FilePathParam();

        // 若指定文件夹没有，则先创建
        File dir = new File(filePathParam.getDownLoadFilePath());
        if (!dir.exists()) {
            if (!dir.mkdirs())
                return null;
        }

        String fileAbPath = filePathParam.getDownLoadFilePath() + File.separator + filename + ".xls";
        File file = FileUtils.getFile(fileAbPath);

        // 如果文件不存在，则重新创建
        if (!file.exists()) {
            try {
                if (!file.createNewFile())
                    return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        WritableWorkbook book = null;
        try {
            // 打开文件
            book = Workbook.createWorkbook(new File(fileAbPath));
            // 生成名为"学生"的工作表，参数0表示这是第一页
            WritableSheet sheet = book.createSheet(filename, 0);
            //写头标题
            sheet.addCell(new Label(0, 0, "姓名"));
            sheet.addCell(new Label(1, 0, "年龄"));
            sheet.addCell(new Label(2, 0, "电话"));
            sheet.addCell(new Label(3, 0, "邮箱"));
            if (list1 != null && !list1.isEmpty()) {
                for (List<Test> list : list1) {
                    for (int i = 0; i < list.size(); i++) {
                        try {
                            sheet.addCell(new Label(0, i + 1, String.valueOf(list.get(i).getName())));
                            sheet.addCell(new Label(1, i + 1, String.valueOf(list.get(i).getAge())));
                            sheet.addCell(new Label(2, i + 1, String.valueOf(list.get(i).getPhone())));
                            sheet.addCell(new Label(3, i + 1, String.valueOf(list.get(i).getEmail())));
                        } catch (WriteException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            // 写入数据并关闭文件
            book.write();
            return fileAbPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (book != null) {
                try {
                    book.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
